//
//  UUChatViewController.swift
//  app4crew
//
//  Created by apple on 16/3/22.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class UUChatViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var chatTableView: UITableView!
    @IBOutlet weak var inputBackView: UUInputView!
    
    @IBOutlet weak var inputViewBottomContraint: NSLayoutConstraint!
    
    var ChatMsgArray = [UUChatModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        chatTableView.estimatedRowHeight = 50;
        ChatMsgArray =  UUChatModel.creatRandomArray(count: 10)
        initBaseViews()
    }
    
    override func viewWillAppear(animated: Bool) {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewDidDisappear(animated: Bool) {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
        self.chatTableView.reloadData()
    }
    
    // private method
    //  名字是。。实际是对屏幕键盘弹出收齐的处理
    @objc func batteryLevelChanged(notification: NSNotification) {
        
        let dict = NSDictionary(dictionary: notification.userInfo!)
        let keyboardValue = dict.objectForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
        let bootomDistance = UIScreen.mainScreen().bounds.size.height - keyboardValue.CGRectValue().origin.y
        let duration = Double(dict.objectForKey(UIKeyboardAnimationDurationUserInfoKey) as! NSNumber);
        
        UIView.animateWithDuration(duration, animations: {
            self.inputViewBottomContraint.constant = bootomDistance
            self.view.layoutIfNeeded()
            }, completion: {
                (value: Bool) in
                let indexPath = NSIndexPath(forRow: self.ChatMsgArray.count-1, inSection: 0)
                self.chatTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true);
        })
    }
    
    
    
    // tableview delegate & dataSource
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.ChatMsgArray.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let model = ChatMsgArray[indexPath.row]
        if model.from == .Me{
            let cell:UUChatRightMessageCell = tableView.dequeueReusableCellWithIdentifier("UUChatRightMessageCell") as! UUChatRightMessageCell
            cell.configUIWithModel(model)
            return cell
        }
        else {
            let cell:UUChatLeftMessageCell = tableView.dequeueReusableCellWithIdentifier("UUChatLeftMessageCell") as! UUChatLeftMessageCell
            cell.configUIWithModel(model)
            return cell
        }
        
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.view.endEditing(true)
    }
    
    func initBaseViews() {
        
        self.title = "任务组聊天"
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Stop, target: self, action: Selector("backAction"))
        //navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Search, target: self, action: nil)
        
        
        inputBackView.sendMessage(
            { [weak self](text:String, textView:UITextView) -> Void in
                self!.ChatMsgArray.append(UUChatModel.creatMessageFromMeByText(text))
                self!.chatTableView.reloadData()
                self!.chatTableView.scrollToBottom(animation: false)
            })


    }
    
    // private method
    
    func backAction(){
        if navigationController?.viewControllers.count>1 {
            self.navigationController?.popViewControllerAnimated(true)
        } else {
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        Common.rootViewController.mainTabBarController.tabBar.hidden = false
    }
    
    func setChatModelList(chatmsglist:[UUChatModel])
    {
        ChatMsgArray = chatmsglist
        self.chatTableView.reloadData()
    }

    
}
